﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.Linq;

namespace ShellTileScheduler
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent ()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke (delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException (object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break ();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        /// 

        static int count = 0;

        protected override void OnInvoke (ScheduledTask task)
        {

            ShellTile TileToFind = ShellTile.ActiveTiles.First ();

            Random _Ran = new Random();

            if (TileToFind != null)
            {
                StandardTileData NewTileData = new StandardTileData
                {
                    Title = _Ran.Next(100).ToString(),
                    // BackgroundImage = new Uri (textBoxBackgroundImage.Text, UriKind.RelativeOrAbsolute),
                    Count = 55,
                    BackTitle = "BackTitle",
                    //  BackBackgroundImage = new Uri (textBoxBackBackgroundImage.Text, UriKind.Relative),
                    BackContent = "BackContent"

                };


                TileToFind.Update (NewTileData);
            }


            if (task.Name == "HelloSchedule")
            {
                ShellToast toast = new ShellToast ();
                toast.Title = "Good: ";
                toast.Content = "Get the Service!";
                toast.Show ();
            }
            else
            {
                //如果不是指定的task, 則代表不需要執行 
            }
            ScheduledActionService.LaunchForTest ("HelloSchedule", TimeSpan.FromSeconds (3));
            NotifyComplete ();
        }
    }
}